//merge census to PIKs using big crosswalk file

/*
use uid pik verflg using "$data/PIK/Census/stata/cen_pik_xwalk_cuf", clear
compress
drop if pik == ""
save "$data/PIK/Census/stata/cen_pik_xwalk_cuf_small", replace //optimized version
*/

//step 1: reshape data to just have kids with parent covariates
local states `"ak al ar az ca co ct de fl ga hi ia id il in ks ky la ma md me mi mn mo ms mt nc nd ne nh nj nm nv ny oh ok or pa ri sc sd tn tx ut va vt wa wi wv wy"'

qui{
foreach state in `states'{
	noi di as result "Working on state `i': `state'"
	use "$temp/census_short_`state'", clear
	local vars `"qsex qdb qspan imprace"'

	//get head covariates
	preserve
	keep if qrel == "01"

	foreach var in `vars'{
		ren `var' `var'_head
	}

	tempfile head
	save `head'
	restore

	//spouse covariates
	preserve
	keep if qrel == "02"

	foreach var in `vars'{
		ren `var' `var'_sp
	}

	tempfile spouse
	save `spouse'
	restore

	//limit to kids and merge
	keep if birth_yr>=1985 & birth_yr<=1994 //kids	
	local vars_personal `"mafid pseq pnc qrel"'
	local vars_house `"rrt stenure"'
	local vars_geo `"bcseq state county tract block blkgrp ur"'
	keep `vars_personal' `vars_house' `vars_geo' //variable restriction
	

	//get parent covariates
	merge m:1 mafid using `head', keep(match) nogen
	merge m:1 mafid using `spouse', keep(match) nogen
	
	//variable renaming
	foreach var in `vars_house'{
		ren `var' `var'_2000
	}

	foreach var in `vars_geo'{
		ren `var' `var'_2000
	}
	
	
	//construct uid for merging
	gen uid = "C" + mafid + pseq + pnc //unique identifier
	compress
	save "$temp/census_short_`state'_pik", replace	
}
}


local states `"ak al ar az ca co ct de fl ga hi ia id il in ks ky la ma md me mi mn mo ms mt nc nd ne nh nj nm nv ny oh ok or pa ri sc sd tn tx ut va vt wa wi wv wy"'
clear

foreach state in `states'{
	append using "$temp/census_short_`state'_pik"
}

//merge on PIKs
merge 1:1 uid using "$data/PIK/Census/stata/cen_pik_xwalk_cuf_small", keep(1 3) nogen //keep non-matches for now. May be useful for inferring stuff in short-form later
save "$temp/census_short_pik_master", replace




//end of do-file

